import { makeAutoObservable, observable } from 'mobx';
import * as api from './api';
import * as dict from '@/services/dict';
import { t } from '@lingui/macro';

export default class ScPriceStore {
  _args = {
    search: {},
    pg: {
      page: 0,
      sort: ['crDate;desc'],
      size: 10,
    },
  };
  total = 0;
  data = [];
  operatingCompanys = [];
  operationCompany = [];
  platformCompany = [];
  loading = false;

  companyIds = [];

  startStation = [];
  endStation = [];

  constructor(rootStore) {
    this.rootStore = rootStore;
    makeAutoObservable(this, { rootStore: false });
  }

  get api() {
    return api;
  }

  /**
   * 使用设置的请求参数和分页配置请求列表数据
   * 分页参数为空时保持当前分页配置
   * @param {object} pgInfo 分页参数
   */
  * query(pgInfo) {
    _.mergeWith(this._args.pg, pgInfo, (o, s) => (_.isArray(o) ? s : undefined)); // 数组直接赋值，不合并
    const { search, pg } = toJS(this._args);
    if (!pg.sort?.length) delete pg.sort;
    this.loading = true;
    try {
      this.total = yield api.count({ search });
      const prices = yield api.search({ search, pg });
      this.data = prices;
    } finally {
      this.loading = false;
    }
  }

  * get(id) {
    const res = yield api.get(id);
    return observable(res);
  }

  * _reload() {
    yield this.query();
  }

  * update(price) {
    const { state } = price;
    yield api.update({ ...price, state: state ? '1' : '0' });
    yield this._reload(price);
  }

  * create(price) {
    const { state } = price;
    yield api.create({ ...price, state: state ? '1' : '0' });
    yield this._reload(price);
  }

  * remove(price) {
    yield api.remove(price.id);
    yield this._reload(price);
  }

  * updateState(price) {
    // eslint-disable-next-line no-param-reassign
    price.state = price.state === '0' ? '1' : '0';
    yield api.update(price);
    yield this.query();
  }

  * getCompany() {
    const res = yield api.getCompany();
    const operation = JSON.stringify(res);
    this.operationCompany = JSON.parse(operation).map((item) => ({
      label: item.name,
      value: item.id,
    }));
    this.platformCompany = [{
      label: '三地通',
      value: 'platform',
    }];
    res.push({
      name: '三地通',
      id: 'platform',
    });
    this.operatingCompanys = res.map((item) => ({
      label: item.name,
      value: item.id,
    }));
  }

  * getShifts(args) {
    const res = yield api.getShifts(args);
    return res;
  }

  async exitingLines(price) {
    const {
      priceType,
      startMainArea,
      endMainArea,
      startMinorAreas,
      endMinorAreas,
      portTypes: ports,
    } = toJS(price);
    return api.existingLines({
      priceType,
      startMainArea,
      endMainArea,
      startMinorAreas: [startMinorAreas],
      endMinorAreas: [endMinorAreas],
      ports,
      excludeId: price.id,
    });
  }

  async existsValidator(rule, value) {
    if (!value) return Promise.resolve();
    try {
      const item = await api.get(value); // 注意get不存在时会抛出404异常
      if (item) return Promise.reject(new Error(t`${value}已存在`));
    } catch (_) {
      return Promise.resolve();
    }
  }

  * getStationShuttle(id) {
    return yield api.getStationShuttle(id);
  }

  * getStartStation(args) {
    const res = yield api.getShuttle(args);
    this.startStation = res.map(({ id, name, siteMapping }) => ({ label: name, value: id, siteMapping }));
  }

  * getEndStation(args) {
    const res = yield api.getShuttle(args);
    this.endStation = res.map(({ id, name, siteMapping }) => ({ label: name, value: id, siteMapping }));
  }

  async getBusStation(args) {
    try {
      const res = await api.getBusStation(args);
      let stations = [];
      for (let i = 0; i < res.length; i++) {
        const e = res[i];
        stations = stations.concat([...e.children]);
      }
      return stations.map(({ id, name }) => ({ label: name, value: id }));
    } catch (error) {
      console.error('站点请求错误', error);
      throw error;
    }
  }

  async getCompanies(args) {
    try {
      const res = await api.getCompanies(args);
      return res.map(({ id, name }) => ({ label: name, value: id }));
    } catch (error) {
      console.error('请求公司列表错误', error);
      throw error;
    }
  }

  async getNoticeUsers() {
    try {
      const res = await dict.searchDictItem('ZGTAccountNoticeUsers');
      return res.map(({ name, fullId }) => ({
        label: name,
        value: fullId,
      }));
    } catch (error) {
      console.error('请求通知人错误', error);
      throw error;
    }
  }

  async getUserInfo(args) {
    try {
      return await api.getUserInfo(args);
    } catch (error) {
      console.error('获取用户错误', error);
      throw error;
    }
  }

  idx(i) {
    return this._args.pg.page * this._args.pg.size + i + 1;
  }

  get pg() {
    return this._args.pg;
  }

  set pg(pg) {
    this.query({ ...pg });
    // _.mergeWith(this._args.pg, pg, (o, s) => (_.isArray(o) ? s : undefined)); // 数组直接赋值，不合并
  }

  get search() {
    this._args.pg.page = 0;
    return this._args.search;
  }

  set search(search) {
    this._args.pg.page = 0;
    this._args.search = search;
    this.query({ page: 0 });
  }
}
